package com.smart.web.controller;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.consts.LeadStatus;
import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.exception.AppRtException;
import com.smart.model.Lead;
import com.smart.model.LeadCond;
import com.smart.model.User;
import com.smart.util.DateUtil;

import jodd.util.StringUtil;

@Controller
public class LeadController extends BaseController{
	
	private SimpleDateFormat sdf = new SimpleDateFormat("MM-dd hh:mm");
	private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	    dateFormat.setLenient(false);
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

	private void checkTeam(User user, String team) {
		if(StringUtil.isEmpty(team)) {
			throw new AppRtException("invalid-param","非法参数");
		}
		if(!user.isInTeam(team)) {
			throw new AppRtException("insufficient-permission", "权限不足");
		}
	}
	
	@RequestMapping(value = "admin/lead/list")
	public String list() {
		return "admin/lead/list";
	}
	
	private void checkKeywords(String keywords) {
		String[] sqlStr = {"exec","execute","insert","select","delete","update","drop","truncate","declare","sitename","net user","xp_cmdshell",
				"grant","group_concat","column_name","information_schema.columns","table_schema","union"};
		for(String key : sqlStr) {
			if(keywords.contains(key)) {
				throw new AppRtException("invalid-keywords", "搜索关键词中有非法字符, 请减少关键词数量继续搜索");
			}
		}
	}
	@RequestMapping(value = "admin/lead/query")
	public @ResponseBody Map<String, Object> query(PageRequest pageRequest, LeadCond cond, 
				String keywords, String beginCrtTimeStr, String endCrtTimeStr, HttpSession session) throws ParseException{
		checkTeam(getCurrentUser(session), cond.getTeam());
		/*
		if(StringUtil.isAllEmpty(keywords, beginCrtTimeStr, endCrtTimeStr)) {
			// 没有搜索关键词，没有搜索时间段， 则属于自然拉取，尝试分配
			synchronized(LeadController.class) {
				leadService.distribute(getCurrentUser(session).getId());
			}
		}*/
		if(StringUtil.isNotEmpty(beginCrtTimeStr)) {
			cond.setBeginCrtTime(sdf1.parse(beginCrtTimeStr));
		}
		else {
			cond.setBeginCrtTime(DateUtil.roundDateToDayBegin(new Date()));
		}
		
		if(StringUtil.isNotEmpty(endCrtTimeStr)) {
			cond.setEndCrtTime(sdf1.parse(endCrtTimeStr));
		}
		else {
			cond.setEndCrtTime(DateUtil.roundDateToDayEnd(new Date()));
		}
		
		cond.addOrderByDesc("updTime");
		Page<Lead> page = null;
		if(StringUtil.isEmpty(keywords)) {
			page = leadService.findAll(pageRequest, cond);
		}
		else {
			page = leadService.findByKeywords(cond, keywords);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page", page);
		map.put("stat", leadService.getLeadStat(cond.getTeam(), cond.getBeginCrtTime(), cond.getEndCrtTime()));
		return map;
	}
	
	@RequestMapping(value = "admin/lead/add", method=RequestMethod.POST)
	public @ResponseBody void editLead(Lead form, HttpSession session) {
		checkTeam(getCurrentUser(session), form.getTeam());
		LeadCond cond = new LeadCond();
		cond.setMobile(form.getMobile());
		/**
		long count = leadService.count(cond);
		if(count>0) {
			throw new AppRtException("duplicated-data", "该数据已存在, 请勿重复添加");
		}**/
		Lead lead = leadService.findOne(cond);
		if(lead!=null) {
			lead.setMobile(lead.getMobile() + "_b");
			leadService.save(lead);
		}
		form.setStatus(LeadStatus.TEL_VERIFIED);
		form.setCrtUserName(getCurrentUser(session).getName());
		form.setSalesUser(getCurrentUser(session));
		leadService.save(form);
	}
	
	@RequestMapping(value = "admin/lead/markWechatFriendReqSent")
	public @ResponseBody String markWechatFriendReqSent(Long id, String wechatName, HttpSession session) {
		Lead lead = leadService.findOne(id);
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			lead.setStatus(LeadStatus.WECHAT_FRIEND_REQ_SENT);
			lead.setWechatName(wechatName);
			lead.setOpUser(getCurrentUser(session));
			leadService.save(lead);
		}
		return "OK";
	}
	
	@RequestMapping(value = "admin/lead/changeWechat")
	public @ResponseBody String changeWechat(Long id, String wechat, HttpSession session) {
		if(StringUtil.isEmpty(wechat)) {
			return "OK";
		}
		Lead lead = leadService.findOne(id);
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			String comment = "微信号变更为" + wechat;
			lead.setLastComment(comment);
			lead.setWechat(wechat);
			String allComment = lead.getAllComment();
			if(StringUtil.isEmpty(allComment)) {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + comment;
			}
			else {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + comment + "\n" + allComment;
			}
			lead.setAllComment(allComment);
			lead.setOpUser(getCurrentUser(session));
			leadService.save(lead);
		}
		return "OK";
	}
	
	@RequestMapping(value = "admin/lead/addComment")
	public @ResponseBody String addComment(Long id, String comment, HttpSession session) {
		Lead lead = leadService.findOne(id);
		if(StringUtil.isEmpty(comment)) {
			return "OK";
		}
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			lead.setLastComment(comment);
			String allComment = lead.getAllComment();
			if(StringUtil.isEmpty(allComment)) {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + comment;
			}
			else {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + comment + "\n" + allComment;
			}
			lead.setAllComment(allComment);
			lead.setOpUser(getCurrentUser(session));
			leadService.save(lead);
		}
		return "OK";
	}
	
	@RequestMapping(value = "admin/lead/markWechatAccepted")
	public @ResponseBody String markWechatAccepted(Long id, String wechatName, HttpSession session) {
		Lead lead = leadService.findOne(id);
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			lead.setStatus(LeadStatus.WECHAT_ACCEPTED);
			lead.setOpUser(getCurrentUser(session));
			lead.setWechatName(wechatName);
			leadService.save(lead);
		}
		return "OK";
	}
	
	@RequestMapping(value = "admin/lead/markWechatRejected")
	public @ResponseBody String markWechatRejected(Long id, String opComment, HttpSession session) {
		Lead lead = leadService.findOne(id);
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			lead.setStatus(LeadStatus.WECHAT_REJECTED);
			lead.setLastComment(opComment);
			String allComment = lead.getAllComment();
			if(StringUtil.isEmpty(allComment)) {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + opComment;
			}
			else {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + opComment + "\n" + allComment;
			}
			lead.setAllComment(allComment);
			lead.setOpUser(getCurrentUser(session));
			leadService.save(lead);
		}
		return "OK";
	}
	
	
	@RequestMapping(value = "admin/lead/markTelReconfirmed")
	public @ResponseBody String markTelReconfirmed(Long id, String salesComment, HttpSession session) {
		Lead lead = leadService.findOne(id);
		if(lead!=null) {
			checkTeam(getCurrentUser(session), lead.getTeam());
			lead.setStatus(LeadStatus.TEL_VERIFIED);
			lead.setLastComment(salesComment);
			String allComment = lead.getAllComment();
			if(StringUtil.isEmpty(allComment)) {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + salesComment;
			}
			else {
				allComment = sdf.format(new Date()) + "->" + super.getCurrentUser(session).getName() + ":" + salesComment + "\n" + allComment;
			}
			lead.setAllComment(allComment);
			lead.setSalesUser(getCurrentUser(session));
			leadService.save(lead);
		}
		return "OK";
	}
	
	@RequestMapping(value = "admin/lead/stat")
	public @ResponseBody Map<String, BigInteger> stat(String team, String from, String to) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		Date fromDate = null;
		Date toDate = null;
		if(from==null) {
			fromDate = DateUtil.roundDateToDayBegin(new Date());
		}
		else {
			fromDate = formatter.parse(from);
		}
		if(to==null) {
			toDate = DateUtil.roundDateToDayEnd(new Date());
		}
		else {
			toDate = formatter.parse(to);
		}
		Map<String, BigInteger> map = leadService.getLeadStat(team, fromDate, toDate);
		return map;
	}
	
	public static void main(String[] args) {
		Date d = DateUtil.roundDateToDayBegin(new Date());
		System.out.println(d);
	}

}
